package com.shj.em.biz.sys.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.shj.em.base.exception.BizException;
import com.shj.em.biz.sys.entity.Cd;
import com.shj.em.biz.sys.mapper.CdMapper;
import com.shj.em.biz.sys.service.CdService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;

/**
 * 代码项值 服务实现类
 *
 * @author Shen Huang Jian
 * @since 2018-07-04
 */
@Service
public class CdServiceImpl extends ServiceImpl<CdMapper, Cd> implements CdService {

    @Autowired
    CdMapper cdMapper;

    public Page<Cd> queryCdPage(Map<String, Object> params){
        int offset = (Integer)params.get("offset");
        int pageSize = (Integer)params.get("limit");
        int pageNo = offset / pageSize + 1;
        Page<Cd> page = new Page(pageNo, pageSize);
        List<Cd> list = cdMapper.queryCdPage(page, params);
        return page.setRecords(list);
    }

    @Cacheable(cacheNames = "codeDescByCodeAndType")
    public List<Cd> queryCdsByType(String type){
        return cdMapper.queryCdsByType(type);
    }

    public Long createCd(Cd cd){
        checkCdAndDescr(cd);
        cdMapper.insert(cd);
        return cd.getId();
    }

    public void updateCd(Cd cd){
        checkCdAndDescr(cd);
        cdMapper.updateById(cd);
    }

    public String getDescrByTypeAndCd(String type, String cd){
        return cdMapper.getDescrByTypeAndCd(type, cd);
    }

    private void checkCdAndDescr(Cd cd){
        boolean isEdit = cd.getId() != null;
        Wrapper<Cd> wrapper = new EntityWrapper<>();
        wrapper.eq("code", cd.getCode()).eq("type_id", cd.getTypeId());
        if(isEdit){
            wrapper.ne("id", cd.getId());
        }

        List<Cd> list = cdMapper.selectList(wrapper);
        if(list != null && list.size() > 0){
            throw new BizException("数据值已存在。");
        }

        /*wrapper = new EntityWrapper();
        wrapper.eq("del_flag",0).eq("description", cd.getDescription()).eq("type_id", cd.getTypeId());
        if(isEdit){
            wrapper.ne("id", cd.getId());
        }

        list = cdMapper.selectList(wrapper);
        if(list != null && list.size() > 0){
            throw new Exception("描述已存在。");
        }*/
    }
}
